package com.cn.wanxi.servlet.user;

import com.alibaba.fastjson.JSONObject;
import com.cn.wanxi.model.PageModel;
import com.cn.wanxi.model.UserModel;
import com.cn.wanxi.service.IUserService;
import com.cn.wanxi.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/back/user/findAll")
public class UserFindAllServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        /**
         * 乱码
         * 拿到前端的值
         * 封装到用户实体类model
         * 调用服务逻辑层
         * 得到结果
         * 返回数据
         */

        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");

        String username = req.getParameter("username");
        String phone = req.getParameter("phone");
        String email = req.getParameter("email");
        String startBirthday = req.getParameter("startBirthday");
        String endBirthday = req.getParameter("endBirthday");
        String sex = req.getParameter("sex");
        String hobby = req.getParameter("hobby");
        String pageNoString = req.getParameter("pageNo");
        String pageSizeString = req.getParameter("pageSize");


        UserModel userModel = new UserModel();
        userModel.setUsername(username == null ? "" : username);
        userModel.setSex(sex);
        userModel.setPhone(phone);
        userModel.setEmail(email);
        userModel.setStartBirthday(startBirthday);
        userModel.setEndBirthday(endBirthday);
        userModel.setHobby(hobby);

        PageModel pageModel = new PageModel();
        int pageNo = 1;
        int pageSize = 10;
        try {
            pageNo = Integer.parseInt(pageNoString);
        } catch (Exception e) {

        }
        try {
            pageSize = Integer.parseInt(pageSizeString);
        } catch (Exception e) {

        }
        pageModel.setPageNo(pageNo);
        pageModel.setPageSize(pageSize);
        userModel.setPageModel(pageModel);
//        userModel.setPageSize(10);
//        userModel.setPageNo(1);
        IUserService iUserService = new UserServiceImpl();
        List<UserModel> list = iUserService.findAll(userModel);
        int count = iUserService.getCount(userModel);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", list);
        jsonObject.put("count", count);
        resp.getWriter().println(jsonObject);


    }
}
